package com.xinyu.config;

import com.xinyu.utils.FileUploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.nio.file.Path;

@Configuration
public class FileResourceConfig implements WebMvcConfigurer {

    private static final Logger log = LoggerFactory.getLogger(FileResourceConfig.class);

    @Value("${file.upload.directory:}")
    private String uploadDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String location = resolveUploadLocation();
        if (location == null) {
            return;
        }
        registry.addResourceHandler("/upload/**")
                .addResourceLocations(location);
    }

    private String resolveUploadLocation() {
        try {
            Path root = FileUploadUtil.resolveWritableRoot(uploadDir);
            String uri = root.toUri().toString();
            if (!uri.endsWith("/")) {
                uri = uri + "/";
            }
            return uri;
        } catch (IOException ex) {
            log.error("无法创建或访问上传目录，静态资源映射失效", ex);
            return null;
        }
    }
}
